<template>
  <div class="users">
    <!-- 面包屑导航 -->
    <el-breadcrumb class="navs" separator="/">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item><a href="/">活动管理</a></el-breadcrumb-item>
      <el-breadcrumb-item>活动列表</el-breadcrumb-item>
      <el-breadcrumb-item>活动详情</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 搜索框 -->
    <div class="user_div">
      <p>用户列表</p>
      <div class="user_div_input">
        <el-input
          @keydown.native.enter="search()"
          placeholder="请输入内容"
          v-model.trim="query"
          class=""
        >
          <el-button
            @click="search()"
            slot="append"
            icon="el-icon-search"
          ></el-button>
        </el-input>
      </div>
    </div>
    <!-- 卡片 -->
    <el-card class="box-card">
      <el-button type="success" size="mini" @click="addUser()">添加</el-button>
    </el-card>
    <!-- 用户列表 -->
    <el-table :data="list.users" border style="width: 100%">
      <el-table-column prop="username" label="姓名" width="150">
      </el-table-column>
      <el-table-column prop="mobile" label="手机号" width="150">
      </el-table-column>
      <el-table-column prop="role_name" label="角色" width="150">
      </el-table-column>
      <el-table-column prop="email" label="邮箱" width="200"> </el-table-column>
      <el-table-column prop="create_time" label="创建时间" width="200">
      </el-table-column>
      <el-table-column label="操作" width="200">
        <template slot-scope="scope">
          <el-button @click="handleEdit(scope.row)" type="primary">编辑</el-button>
          <el-button @click="handleDel(scope.row)" type="primary">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页条 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pagenum"
      :page-sizes="[5, 10, 20, 50]"
      :page-size="pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="list.total"
    >
    </el-pagination>
    <!-- 弹出框 -->
    <el-dialog title="添加用户" :visible.sync="dialogVisible" width="50%">
      <!-- 表单 -->
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="姓名" prop="username">
          <el-input v-model="ruleForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="ruleForm.password"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="ruleForm.mobile"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="ruleForm.email"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm')"
            >添加</el-button
          >
          <el-button @click="resetForm('ruleForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
import { Message } from "element-ui";
import { MessageBox } from 'element-ui';
export default {
  name: "User",
  data() {
    // 邮箱验证
    var validateemail = (rule, value, callback) => {
      if (
        !/^[A-Za-z\d]+([-_.][A-Za-z\d]+)*@([A-Za-z\d]+[-.])+[A-Za-z\d]{2,4}$/.test(
          value
        )
      ) {
        callback(new Error("邮箱格式不正确"));
      } else {
        callback();
      }
    };
    // 手机号验证
    var validatemobile = (rule, value, callback) => {
      if (!/^1[3,5,7,8,9]\d{9}$/.test(value)) {
        callback(new Error("手机号格式不正确"));
      } else {
        callback();
      }
    };
    return {
      query: "",
      pagenum: 1,
      pagesize: 5,
      list: {},
      dialogVisible: false,
      ruleForm: {
        username: "",
        password: "",
        mobile: "",
        email: "",
      },
      rules: {
        username: [{ required: true, message: "请输入姓名", trigger: "blur" }],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
        email: [{ validator: validateemail, trigger: "blur" }],
        mobile: [{ validator: validatemobile, trigger: "blur" }],
      },
    };
  },
  methods: {
    // 编辑
    handleEdit(a){
      console.log(a.id);
    },
    // 删除
    handleDel(a){
      this.$confirm('是否要删除该用户?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          var p = await this.axios.delete("users/"+a.id)
          if (p.data.meta.status == 200) {
            this.$message({
              type: 'success',
              message: p.data.meta.msg
            });
            // 加载列表
            this.getList();
          }else{
            this.$message({
              type: 'success',
              message: p.data.meta.msg
            });
          }
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
    },
    // 添加用户
    addUser() {
      this.dialogVisible = true;
    },
    // 获取用户列表
    async getList() {
      var p = await this.axios.get(
        `users?query=${this.query}&pagenum=${this.pagenum}&pagesize=${this.pagesize}`
      );
      console.log(p);
      this.list = p.data.data;
    },
    // 每页数据发生改变
    handleSizeChange(val) {
      this.pagesize = val;
      this.getList();
      console.log(`每页 ${val} 条`);
    },
    //   改变页码触发
    handleCurrentChange(val) {
      this.pagenum = val;
      this.getList();
      console.log(`当前页: ${val}`);
    },
    // 搜索
    search() {
      this.getList();
    },
    // 创建用户  表单验证
    submitForm(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          var str = `username=${this.ruleForm.username}&password=${this.ruleForm.password}&mobile=${this.ruleForm.mobile}&email=${this.ruleForm.email}`;
          var p = await this.axios.post("users", str);
          // console.log(p);
          if (p.data.meta.status == 201) {
            Message({
              showClose: true,
              message: p.data.meta.msg,
              type: "success",
            });
            // 隐藏弹出框
            this.dialogVisible = false;
            // 重新加载列表
            this.getList();
          }else{
            Message({
              showClose: true,
              message: p.data.meta.msg,
              type: "success",
            });
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
  },
  mounted() {
    this.getList();
  },
};
</script>
<style lang="scss">
body {
  background: #e9eef3;
}
.navs {
  margin: 20px 15px;
}
.user_div {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-left: 20px;
  .user_div_input {
    width: 400px;
    margin-left: 800px;
  }
}
</style>
